package com.zbkj.service.service.saleroom.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.product.ProductAttrValue;
import com.zbkj.common.model.saleroom.RoomProduct;
import com.zbkj.common.model.saleroom.SaleRoom;
import com.zbkj.common.model.saleroom.TransferInfo;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.TransferInfoRequest;
import com.zbkj.service.dao.ProductAttrValueDao;
import com.zbkj.service.dao.saleroom.RoomProductDao;
import com.zbkj.service.dao.saleroom.TransferInfoDao;
import com.zbkj.service.service.UserService;
import com.zbkj.service.service.saleroom.ITransferInfoService;
import com.zbkj.service.service.saleroom.RoomProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 调货详情Service业务层处理
 *
 * @author zkf
 * @date 2025-02-21
 */
@Service
public class TransferInfoServiceImpl extends ServiceImpl<TransferInfoDao, TransferInfo> implements ITransferInfoService {

    @Autowired
    private TransferInfoDao transferInfoDao;
    @Autowired
    private RoomProductDao roomProductDao;
    @Autowired
    private RoomProductService roomProductService;
    @Autowired
    private ProductAttrValueDao productAttrValueDao;
    @Autowired
    private UserService userService;


    /**
     * 查询调货详情
     *
     * @param id 调货详情主键
     * @return 调货详情
     */
    @Override
    public TransferInfo selectTransferInfoById(Long id) {
        TransferInfo transferInfo = transferInfoDao.selectTransferInfoById(id);
        if (transferInfo != null && StrUtil.isNotBlank(transferInfo.getTransferJson())) {
            List<TransferInfoRequest> transferInfoRequests = JSONArray.parseArray(transferInfo.getTransferJson(), TransferInfoRequest.class);
            transferInfo.setTransferInfoRequestList(transferInfoRequests);
        }
        return transferInfo;
    }

    /**
     * 查询调货详情列表
     *
     * @param transferInfo 调货详情
     * @return 调货详情
     */
    @Override
    public PageInfo<TransferInfo> selectTransferInfoList(TransferInfo transferInfo, PageParamRequest pageParamRequest) {
        Page<TransferInfo> articlePage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<TransferInfo> list = transferInfoDao.selectTransferInfoList(transferInfo);
        list.forEach(t -> {
            String transferJson = t.getTransferJson();
            if (StrUtil.isNotBlank(transferJson)) {
//                List<TransferInfoRequest> transferInfoRequests = Convert.toList(TransferInfoRequest.class, transferJson);
                List<TransferInfoRequest> transferInfoRequests = JSONArray.parseArray(transferJson, TransferInfoRequest.class);
                t.setTransferInfoRequestList(transferInfoRequests);
            }
        });

        return CommonPage.copyPageInfo(articlePage, list);
    }

    /**
     * 新增调货详情
     *
     * @param transferInfo 调货详情
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = CrmebException.class)
    public int insertTransferInfo(TransferInfo transferInfo) {
        List<TransferInfoRequest> transferInfoRequestList = transferInfo.getTransferInfoRequestList();
        List<Integer> productSpecsIdList = transferInfoRequestList.stream().map(m -> m.getProductSpecsId()).collect(Collectors.toList());
        Map<Integer, ProductAttrValue> integerProductAttrValueMap = productAttrValueDao.selectListByIdList(productSpecsIdList);
        transferInfoRequestList.forEach(transferInfoRequest -> {
            Integer productSpecsId = transferInfoRequest.getProductSpecsId();
            ProductAttrValue productAttrValue = integerProductAttrValueMap.get(productSpecsId);
//            ProductAttrValue productAttrValue = productAttrValueDao.selectById(productSpecsId);
            if (productAttrValue == null) {
                throw new CrmebException("商品规格id不存在");
            }
            if (productAttrValue.getStock() <= 0) {
                throw new CrmebException(productAttrValue.getSku() + " 商品规格库存数量为0,不支持调货");
            }
            if (productAttrValue.getStock() < transferInfoRequest.getTransferNumber()) {
                throw new CrmebException(productAttrValue.getSku() + " 调货数量不能超过规格库存数量");
            }
        });
        transferInfo.setTransferJson(JSON.toJSONString(transferInfoRequestList));
        int i = transferInfoDao.insert(transferInfo);
//        transferInfoRequestList.forEach(transferInfoRequest -> {
//            LambdaQueryWrapper<RoomProduct> lqw = new LambdaQueryWrapper();
//            lqw.eq(RoomProduct::getRoomId, transferInfo.getTransferRoomId());
//            lqw.eq(RoomProduct::getProductSpecsId, transferInfoRequest.getProductSpecsId());
//            RoomProduct roomProduct = roomProductDao.selectOne(lqw);
//            if (null != roomProduct) {
//                roomProduct.setProductStore(roomProduct.getProductStore() + transferInfoRequest.getTransferNumber());
//                roomProductDao.updateById(roomProduct);
//            } else {
//                RoomProduct r = new RoomProduct()
//                        .setTransferInfoId(transferInfo.getId())
//                        .setRoomId(transferInfo.getTransferRoomId())
//                        .setProductId(transferInfoRequest.getProductId())
//                        .setProductSpecsId(transferInfoRequest.getProductSpecsId())
//                        .setProductStore(transferInfoRequest.getTransferNumber())
//                        .setCreateTime(new Date());
//                roomProductDao.insert(r);
//            }
//        });
        return i;
    }


    /**
     * 修改调货详情
     *
     * @param transferInfo 调货详情
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = CrmebException.class)
    public int updateTransferInfo(TransferInfo transferInfo) {
        List<TransferInfoRequest> transferInfoRequestList = transferInfo.getTransferInfoRequestList();
        transferInfo.setTransferJson(JSON.toJSONString(transferInfo.getTransferInfoRequestList()));

        transferInfoRequestList.forEach(transferInfoRequest -> {
            LambdaQueryWrapper<RoomProduct> lqw = new LambdaQueryWrapper();
            lqw.eq(RoomProduct::getRoomId, transferInfo.getTransferRoomId());
            lqw.eq(RoomProduct::getProductSpecsId, transferInfoRequest.getProductSpecsId());
//            lqw.eq(RoomProduct::getIsSure, 0);
            RoomProduct roomProduct = roomProductDao.selectOne(lqw);
            if (null != roomProduct) {
                roomProduct.setProductStore(transferInfoRequest.getTransferNumber());
                roomProductDao.updateById(roomProduct);
            } else {
                RoomProduct r = new RoomProduct()
                        .setTransferInfoId(transferInfo.getId())
                        .setRoomId(transferInfo.getTransferRoomId())
                        .setProductId(transferInfoRequest.getProductId())
                        .setProductSpecsId(transferInfoRequest.getProductSpecsId())
                        .setProductStore(transferInfoRequest.getTransferNumber())
                        .setCreateTime(new Date());
                roomProductDao.insert(r);
            }
        });
        return transferInfoDao.updateTransferInfo(transferInfo);
    }


    /**
     * 批量删除调货详情
     *
     * @param ids 需要删除的调货详情主键
     * @return 结果
     */
    @Override
    public int deleteTransferInfoByIds(Long[] ids) {
        return transferInfoDao.deleteTransferInfoByIds(ids);
    }

    /**
     * 删除调货详情信息
     *
     * @param id 调货详情主键
     * @return 结果
     */
    @Override
    public int deleteTransferInfoById(Long id) {
        return transferInfoDao.deleteTransferInfoById(id);
    }


    /**
     * 查询调货详情列表
     *
     * @param pageParamRequest
     * @return
     */
    @Override
    public PageInfo<TransferInfo> selectTransferInfoListByRoomId(PageParamRequest pageParamRequest) {
        SaleRoom saleRoom = userService.getSaleRoomInfo();
        Page<TransferInfo> articlePage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<TransferInfo> list = transferInfoDao.selectTransferInfoListByRoomId(saleRoom.getId());
        list.forEach(t -> {
            String transferJson = t.getTransferJson();
            if (StrUtil.isNotBlank(transferJson)) {
                List<TransferInfoRequest> transferInfoRequests = JSONArray.parseArray(transferJson, TransferInfoRequest.class);
                t.setTransferInfoRequestList(transferInfoRequests);
            }
        });
        return CommonPage.copyPageInfo(articlePage, list);
    }

    public static void main(String[] args) throws Exception {
        String data = "ABC123";
        int width = 300;
        int height = 100;

        BitMatrix matrix = new MultiFormatWriter()
                .encode(data, BarcodeFormat.CODE_128, width, height);

        MatrixToImageWriter.writeToPath(
                matrix, "PNG", java.nio.file.Paths.get("barcode.png")
        );
    }

    @Override
    @Transactional(rollbackFor = CrmebException.class)
    public Boolean isSure(Integer transferInfoId) {
//        LambdaUpdateWrapper<TransferInfo> luw = new LambdaUpdateWrapper();
//        luw.set(TransferInfo::getIsSure, 1);
//        luw.eq(TransferInfo::getId, transferInfoId);
//        update(luw);
        TransferInfo transferInfo = getById(transferInfoId);
        transferInfo.setIsSure(1);
        updateById(transferInfo);

        List<TransferInfoRequest> transferInfoRequests = JSONArray.parseArray(transferInfo.getTransferJson(), TransferInfoRequest.class);
        transferInfoRequests.forEach(transferInfoRequest -> {
            LambdaQueryWrapper<RoomProduct> lqw = new LambdaQueryWrapper();
            lqw.eq(RoomProduct::getRoomId, transferInfo.getTransferRoomId());
            lqw.eq(RoomProduct::getProductSpecsId, transferInfoRequest.getProductSpecsId());
            RoomProduct roomProduct = roomProductDao.selectOne(lqw);
            if (null != roomProduct) {
                roomProduct.setProductStore(roomProduct.getProductStore() + transferInfoRequest.getTransferNumber());
                roomProductDao.updateById(roomProduct);
            } else {
                RoomProduct r = new RoomProduct()
                        .setTransferInfoId(transferInfo.getId())
                        .setIsSure(1)
                        .setRoomId(transferInfo.getTransferRoomId())
                        .setProductId(transferInfoRequest.getProductId())
                        .setProductSpecsId(transferInfoRequest.getProductSpecsId())
                        .setProductStore(transferInfoRequest.getTransferNumber())
                        .setCreateTime(new Date());
                roomProductDao.insert(r);
            }
            //减去相应仓库的库存
            productAttrValueDao.updateByIdAndTransferNumber(transferInfoRequest.getProductSpecsId(),transferInfo.getTransferRoomId(), transferInfoRequest.getTransferNumber());

        });

        return true;
    }


}